/*
 ============================================================================
 Name        : channel_init.c
 Author      : chenf
 Version     : 1.0
 Copyright   : loongsec
 Description : channel_init in C, Ansi-Code
 ============================================================================
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "sqlite3.h"
#include "cgi.h"
#include "cookie.h"

sqlite3 *db = NULL;
int  nrow=0,ncolumn=0;
char **azResult = NULL;
char *zErrMsg =0;
char sql[1000];

/* if has channel return 0, else 1.*/
int has_channel(PARAM channelIndex){
    sprintf(sql, "select * from [tb_channel_parm] where channel_index = %s ", channelIndex.value);
    int rc = sqlite3_get_table(db,sql,&azResult,&nrow,&ncolumn,&zErrMsg);
    if (rc != SQLITE_OK) {
        fprintf(stderr,"SQL error:%s\n", zErrMsg);
        sqlite3_close(db);
        return 0;

    }
    if (*azResult != NULL) {
        if(nrow >= 1){
            return 0;
        }else{
            return 1;
        }
    }
    return 1;
}

int clear_channel(PARAM phaseIndex){
    sprintf(sql, " UPDATE [TB_CHANNEL_PARM] \
                set [channel_ctrl_signal_source] = 0, \
                    [last_modified] = datetime(CURRENT_TIMESTAMP,'localtime') \
                WHERE [channel_ctrl_signal_source] = %s ;", phaseIndex.value);
    //printf("sql: %s\n", sql);
    int sr = sqlite3_exec(db, sql, 0, 0, &zErrMsg);
    return sr;
}

int update_channel(PARAM channelIndex, PARAM phaseIndex){
    sprintf(sql, " UPDATE [TB_CHANNEL_PARM] \
                set [channel_ctrl_signal_source] = %s, \
                    [last_modified] = datetime(CURRENT_TIMESTAMP,'localtime') \
                WHERE [channel_index] = %s ;", phaseIndex.value, channelIndex.value);
    //printf("sql: %s\n", sql);
    int sr = sqlite3_exec(db, sql, 0, 0, &zErrMsg);
    return sr;
}

int new_channel(PARAM channelIndex, PARAM phaseIndex){
    sprintf(sql, "INSERT INTO [TB_CHANNEL_PARM] (\
                [channel_index],\
                [channel_ctrl_signal_source],\
                [automatic_flash_channel_state], \
                [channel_ctrl_type], \
                [last_modified] ) \
                VALUES (%s, %s, 0, 0, datetime(CURRENT_TIMESTAMP,'localtime') );",
                channelIndex.value, phaseIndex.value);
    //printf("sql: %s\n", sql);
    int sr = sqlite3_exec(db, sql, 0, 0, &zErrMsg);
    return sr;
}

int main(void) {
    char *input;
    char *req_method;
    int  rc;

    if(isvalid_cookie()!=0){
        return 0;
    }
    rc = sqlite3_open(PATH_DATABASE,&db);
    printf("Content-type:text/json;charset=utf-8\n\n");
    if (rc) {
        fprintf(stderr,"Can't open database:%s\n",sqlite3_errmsg(db));
        sqlite3_close(db);
        return 0;
    } else {
        req_method = getenv("REQUEST_METHOD");
        FILE* fp = (FILE*) stdin;
        input = getcgidata(fp, req_method);
        //PARAM un = getParam(input, "username");
        //printf("Your find is %s = %s  \n", un.key, un.value );
        PARAM method  = getParam(input, "method");
        PARAM channel_index[50];
        int si = getParams(input, "phase_channel_id", channel_index);
        PARAM phase_index = getParam(input, "phaseIndex");
        //printf("channel_index: %d\n\n", si);
        int t = 0;
        int r = clear_channel(phase_index);
        for(t=0; t<si; t++){
            if( has_channel(channel_index[t]) == 0 ){
                r = update_channel(channel_index[t], phase_index);
                //printf("has %s, %d \n", channel_index[t].value, r);
            } else {
                r = new_channel(channel_index[t], phase_index);
                //printf("not has %s,%d \n", channel_index[t].value, r);
            }
        }
        //printf("SQL: %s", sql);
        sqlite3_close(db);//关闭数据库
        printf("{\"res\":\"%d\",\"msg\":\"%s\"}", 0, sqlite3_errmsg(db));
        return 0;
    }
    fflush(stdout);
    return EXIT_SUCCESS;
}
